﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace HttpHelper
{
    /// <summary>
    /// Http方法
    /// </summary>
    public class HttpMethods
    {
        private static EContentType _Et = EContentType.ApplicationForm;
        /// <summary>
        /// 请求方式
        /// </summary>
        public static EContentType Et
        {
            get
            {
                return _Et;
            }
            set
            {
                _Et = value;
                SetGetContentType(value);
            }
        }
        /// <summary>
        /// 提交头
        /// </summary>
        public static string ContentType { get; set; }
        /// <summary>
        /// Cookie
        /// </summary>
        public static CookieContainer Cookies { get; set; }
        /// <summary>
        /// Refer
        /// </summary>
        public static string ReferUrl { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ct"></param>
        public static void SetGetContentType(EContentType ct)
        {
            switch (ct)
            {
                case EContentType.ApplicationForm:
                    ContentType = "application/x-www-form-urlencoded";
                    break;
                case EContentType.ApplicationJson:
                    ContentType = "application/json";
                    break;
                case EContentType.MultipartForm:
                    ContentType = "multipart/form-data";
                    break;
                case EContentType.TextXml:
                    ContentType = "text/xml";
                    break;
                case EContentType.ApplicationFromCode:
                    ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                    break;
            }
        }
        #region 日志输出
        /// <summary>
        /// 日志输出
        /// </summary>
        /// <param name="str">输出字符串</param>
        public static void LogOut(string str)
        {
            string path = @"netLog.log";
            if (!File.Exists(path))
            {

                FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(str + "时间是:" + DateTime.Now.ToString());
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs2 = new FileStream(path, FileMode.Append, FileAccess.Write);
                StreamWriter se = new StreamWriter(fs2);
                se.WriteLine(str + "时间是:" + DateTime.Now.ToString() + "\n");
                se.Close();
                fs2.Close();
            }
        }
        #endregion

        #region POST提交
        /// <summary>
        /// Post提交
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postdata">提交信息</param>
        /// <returns>返回list的对象</returns>
        public static HttpResponseResult PostData(string url, string postdata, CookieContainer cookies, Encoding encodings, List<HeaderType> HeaderList)
        {
            HttpResponseResult ResponseReult = new HttpResponseResult();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
            request.Referer = ReferUrl;
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] b = encodings.GetBytes(postdata);

            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword,application/json, text/plain, */*";
            request.UserAgent = " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0";

            request.ContentType = ContentType;
            if (HeaderList != null)
            {
                for (int index = 0; index < HeaderList.Count; index++)
                {
                    try
                    {
                        request.Headers.Add(HeaderList[index].Header, HeaderList[index].Value);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            request.Method = "POST";
            request.CookieContainer = cookies;
            request.KeepAlive = true;
            request.ContentLength = b.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(b, 0, b.Length);
            }
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse() as HttpWebResponse)
                {
                    HttpStatusCode s = response.StatusCode;
                    ResponseReult.StatusCode = response.StatusCode;
                    ResponseReult.ReturnMsg = response.StatusDescription;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), encodings))
                    {
                        ResponseReult.ContentData = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                ResponseReult.StatusCode = HttpStatusCode.NoContent;
                ResponseReult.ReturnMsg = "请求发生异常，详细信息请看日志";
                LogOut("POST获取出错，出错信息是" + e.Message.ToString());
            }
            return ResponseReult;

        }
        #endregion

        #region Get获取数据
        /// <summary>
        /// GET方法
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>返回list对象</returns>
        public static HttpResponseResult Get(string url, CookieContainer cookies, Encoding encodings)
        {
            HttpResponseResult ResponseReult = new HttpResponseResult();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
                request.Referer = ReferUrl;
                request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
                request.ContentType = ContentType;// string.IsNullOrWhiteSpace(ContentType) ? "application/x-www-form-urlencoded" : ContentType;
                request.Method = "GET";
                request.AllowAutoRedirect = false;
                request.CookieContainer = cookies;
                request.KeepAlive = true;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    HttpStatusCode s = response.StatusCode;
                    ResponseReult.StatusCode = response.StatusCode;
                    ResponseReult.ReturnMsg = response.StatusDescription;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), encodings))
                    {
                        ResponseReult.ContentData = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                ResponseReult.StatusCode = HttpStatusCode.NoContent;
                ResponseReult.ReturnMsg = "请求发生异常，详细信息请看日志";
                LogOut("Get" + url + "获取出错，出错信息是" + e.Message.ToString());
            }
            return ResponseReult;
        }
        #endregion

        #region Get获取文件
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="str">请求地址</param>
        /// <returns>list(Byte)对象</returns>
        public static HttpResponseResult GetFile(string str, string path, CookieContainer cookies)
        {
            HttpResponseResult ResponseReult = new HttpResponseResult();
            Console.WriteLine("执行GetFile方法！" + DateTime.Now);
            bool bol = true;
            //   ArrayList list = new ArrayList();
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(str);
            //属性配置   
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            webRequest.MaximumResponseHeadersLength = -1;
            webRequest.CookieContainer = cookies;
            webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg,image/png,image/jpg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, " +
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*";
            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            webRequest.ContentType = ContentType;
            webRequest.Method = "GET";
            //webRequest.Headers.Add("Accept-Language", "zh-cn");
            //webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            webRequest.KeepAlive = true;
            List<byte> list = new List<byte>();
            try
            {
                //获取服务器返回的资源   "
                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    HttpStatusCode s = webResponse.StatusCode;
                    ResponseReult.StatusCode = webResponse.StatusCode;
                    ResponseReult.ReturnMsg = webResponse.StatusDescription;
                    using (Stream sream = webResponse.GetResponseStream())
                    {
                        while (true)
                        {
                            int data = sream.ReadByte();
                            if (data == -1)
                                break;
                            list.Add((byte)data);
                        }
                        //FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite,FileShare.ReadWrite);
                        //fs.Write(list.ToArray(), 0, list.ToArray().Length);
                        //fs.Close();
                        //StreamWriter sw = new StreamWriter(fs);
                        //sw.wr
                        ResponseReult.ContentData = list.ToArray();
                        File.WriteAllBytes(path, list.ToArray());
                        Console.WriteLine("执行GetFile方法完成！" + DateTime.Now);
                    }
                }
            }
            catch (WebException ex)
            {
                ResponseReult.StatusCode = HttpStatusCode.NoContent;
                ResponseReult.ReturnMsg = "请求发生异常，详细信息请看日志";
                LogOut("GetFile获取出错，出错信息是" + ex.Message.ToString());
            }
            return ResponseReult;
        }
        #endregion

        #region 获取Cookie

   

        /// <summary>
        /// 获取网站Cookie
        /// </summary>
        /// <param name="url">获得Cookie地址</param>
        /// <returns></returns>
        public static CookieContainer getCookie(string url)
        {

            CookieContainer myCookieContainer = new CookieContainer();
            try
            {
                //新建一个CookieContainer
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                myHttpWebRequest.Timeout = 50 * 1000;
                myHttpWebRequest.Accept = "text/html,application/xhtml+xml,*/*";
                myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
                myHttpWebRequest.KeepAlive = true;
                myHttpWebRequest.CookieContainer = new CookieContainer();
                HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                myCookieContainer = myHttpWebRequest.CookieContainer;
                string cookie = response.Headers.Get("Set-Cookie");
                //foreach (Cookie ck in response.Cookies)
                //{
                //    myCookieContainer.Add(ck);
                //}
                //res.Cookies = myHttpWebRequest.CookieContainer.GetCookies(new Uri(http://www.baidu.com));
                response.Close();
                ////新建一个HttpWebRequest
                //myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                //myHttpWebRequest.AllowAutoRedirect = false;
                //myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
                //myHttpWebRequest.Timeout = 60000;
                //myHttpWebRequest.KeepAlive = true;

                //myHttpWebRequest.Method = "GET";
                //myHttpWebRequest.CookieContainer = myCookieContainer;
                ////设置HttpWebRequest
                //Stream myRequestStream = myHttpWebRequest.GetRequestStream();

                //HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                //foreach (Cookie ck in myHttpWebResponse.Cookies)
                //{
                //    myCookieContainer.Add(ck);
                //}
                //myHttpWebResponse.Close();
            }
            catch (Exception e)
            {
                LogOut("Cookies获取出错，出错信息是" + e.Message.ToString());
            }
            return myCookieContainer;
        }
    }
    #endregion
}

